let isFirstLoad = true; // 标记是否首次加载
let currentEffectIndex = 0; // 当前应用的动画索引
const effects = ["zoom", "fade", "rotate"]; // 动画效果列表
let isLoading = false; // 标记是否正在加载图片
let currentImageURL = ""; // 当前展示的图片 URL

// 设置背景图片
function setBackground(apiUrl) {
  if (isLoading) return; // 避免重复加载
  isLoading = true;

  const loadingIndicator = document.getElementById("loading-indicator");

  // 首次加载时显示加载动画
  if (isFirstLoad) {
    loadingIndicator.style.display = "flex";
  }

  fetch(apiUrl)
    .then((response) => response.blob())
    .then((imageBlob) => {
      const imageObjectURL = URL.createObjectURL(imageBlob);
      currentImageURL = imageObjectURL; // 保存当前图片的 URL
      document.body.style.backgroundImage = `url(${imageObjectURL})`;
      applyEffect(); // 应用动画效果
      showDownloadButton(); // 显示下载按钮
    })
    .catch((error) => console.error("Error fetching the image:", error))
    .finally(() => {
      if (isFirstLoad) {
        loadingIndicator.style.display = "none";
        isFirstLoad = false;
      }
      isLoading = false;
    });
}

// 应用动画效果
function applyEffect() {
  const effectClasses = effects.map((effect) => `effect-${effect}`);
  document.body.classList.remove(...effectClasses);

  const effectClass = `effect-${effects[currentEffectIndex]}`;
  document.body.classList.add(effectClass);

  currentEffectIndex = (currentEffectIndex + 1) % effects.length; // 循环切换效果
}

// 显示下载按钮
function showDownloadButton() {
  const downloadButton = document.getElementById("download-button");
  downloadButton.style.display = "block";
}

// 下载背景图片
function downloadImage() {
  if (!currentImageURL) {
    console.error("No image to download.");
    return;
  }

  const link = document.createElement("a");
  link.href = currentImageURL; // 使用当前图片的 URL
  link.download = "background.jpg"; // 下载的文件名
  link.click();
}

// 检测方向并获取图片 URL
function detectOrientation() {
  const path = window.location.pathname;

  let apiUrl = "";
  if (path === "/vertical") {
    apiUrl = "https://api.jiazhen.wang/image/api/vertical";
  } else if (path === "/horizontal") {
    apiUrl = "https://api.jiazhen.wang/image/api/horizontal";
  } else if (path === "/adaptive") {
    const isPortrait = window.innerHeight > window.innerWidth;
    apiUrl = isPortrait
      ? "https://api.jiazhen.wang/image/api/vertical"
      : "https://api.jiazhen.wang/image/api/horizontal";
  } else {
    console.log(path);
    console.log("Unknown path, returning 404.");
    return new Response("404 Not Found", { status: 404 });
  }

  setBackground(apiUrl);
}

// 初始加载
detectOrientation();

// 每 20 秒切换背景
setInterval(detectOrientation, 20000);

// 添加下载按钮
const downloadButton = document.createElement("button");
downloadButton.id = "download-button";
downloadButton.innerText = "下载图片";
downloadButton.onclick = downloadImage;
document.body.appendChild(downloadButton);
